﻿using System;
using System.Collections.Generic;
using System.Device.Location;
using Microsoft.Phone.Reactive;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;


namespace WP7SampleProject12
{

    public static class Location
    {
        public static String state = "NA";
        public static String city = "NA";
        public static Double latitude = -1;
        public static Double longitude = -1;
        public static bool updated = false;
    }

    public static class GlobalVariables
    {
    
        public static string movieName= "";
        public static int stage = 0;
        public static String positive = "NA";
        public static String negative = "NA";

    }

    public class movieItem
    {
        
        public string MovieName { get; set; }
        public string MovieInfo { get; set; }
    
    }

    public partial class MainPage : PhoneApplicationPage
	{

		public MainPage()
		{
            bool UpdateAvailable = true;
            // Check for Software updates
            if ((GlobalVariables.movieName.Equals("") ) && (UpdateAvailable))
            {
                MessageBoxButton b = new MessageBoxButton();
                MessageBox.Show("New update for the software is available.\n Visit www.tweetmyflick.com  to download.", "UPDATE", b);
            }
            
            InitializeComponent();
            
            location();
            progressBar.IsIndeterminate = true;
            PageTitle0.Visibility = System.Windows.Visibility.Collapsed;
            PageTitle1.Visibility = System.Windows.Visibility.Collapsed;
            PageTitle2.Visibility = System.Windows.Visibility.Collapsed;
            movieName.Visibility = System.Windows.Visibility.Collapsed;
            button.Visibility = System.Windows.Visibility.Collapsed;
            
            movieList();
            progressBar.IsIndeterminate = false;
            PageTitle0.Visibility = System.Windows.Visibility.Visible;
            PageTitle1.Visibility = System.Windows.Visibility.Visible;
            PageTitle2.Visibility = System.Windows.Visibility.Visible;
            movieName.Visibility = System.Windows.Visibility.Visible;
            button.Visibility = System.Windows.Visibility.Visible;

            SlideTransition rotatetransition = new SlideTransition();
            rotatetransition.Mode = SlideTransitionMode.SlideLeftFadeIn;
            ITransition transition;
            transition = rotatetransition.GetTransition(PageTitle0);
            transition.Completed += delegate { transition.Stop(); };
            
            transition.Begin();

            rotatetransition = new SlideTransition();
            rotatetransition.Mode = SlideTransitionMode.SlideUpFadeIn;
            transition = rotatetransition.GetTransition(PageTitle1);
            transition.Completed += delegate { transition.Stop(); };
            transition.Begin();

            rotatetransition = new SlideTransition();
            rotatetransition.Mode = SlideTransitionMode.SlideRightFadeIn;
            transition = rotatetransition.GetTransition(PageTitle2);
            transition.Completed += delegate { transition.Stop(); };
            transition.Begin();
            
            TurnstileTransition trns ;
            trns = new TurnstileTransition();
            trns.Mode = TurnstileTransitionMode.BackwardIn;
            transition = trns.GetTransition(LayoutRoot);
            transition.Completed += delegate { transition.Stop(); };
            transition.Begin();
            
		}

        private void movieEarning(object sender, RoutedEventArgs e)
        {
            var task = new Microsoft.Phone.Tasks.WebBrowserTask
            {
                URL = "https://docs.google.com/spreadsheet/ccc?key=0AqaJTr3dMemMdHdqQktZOXF1RTF3bDlrWDd1Vkw5N2c&single=true&gid=0&output=html"
            };

            task.Show();
        }
        
        
        List<String> movieList0 = new List<String>();
        bool donemovieList = false;

        private void location()
        {
                String URL = "http://facemeifudare.appspot.com/ip";
                WebClient Location = new WebClient();
                Location.DownloadStringCompleted += new DownloadStringCompletedEventHandler(getLocation);
                Location.DownloadStringAsync(new Uri(URL));
            
        }

        void getLocation(object sender, DownloadStringCompletedEventArgs e)
        {
            if (!Location.updated)
            {
                try
                {
                    String[] locationVars = e.Result.Split('\n');
                    Location.city = locationVars[0];
                    Location.state = locationVars[1];
                    Location.latitude = Convert.ToDouble(locationVars[2]);
                    Location.longitude = Convert.ToDouble(locationVars[3]);
                    Location.updated = true;
                }

                catch (Exception exp)
                {
                    MessageBox.Show("Cannot determine your location. Please enter your location for better results");
                }
             }
        }
        
        private List<String> movieList()
        {
            //returns the list of Movies
            String URL;
            if (Location.updated)
                URL = "http://facemeifudare.appspot.com/movielist?location=" + Location.city + " " + Location.state;
            else
                URL = "http://facemeifudare.appspot.com/movielist?location=Bangalore";
            WebClient twitter = new WebClient();
            twitter.DownloadStringCompleted += new DownloadStringCompletedEventHandler(DownloadStringCompletedURL);
            twitter.DownloadStringAsync(new Uri(URL));
            return movieList0;
        }

        void DownloadStringCompletedURL(object sender, DownloadStringCompletedEventArgs e)
        {
            if (donemovieList == false)
            {
                donemovieList = true;

                String Result = e.Result;
                foreach (String inp in Result.Split('\n'))
                      movieList0.Add(inp.ToLower().Trim());
             }
        }

        private bool isCorrect(String movieName)
        {
            List<String> movies = movieList();
            foreach (String movie in movies)
            {
                if ((movie.ToLower().Split('%')[0].Trim().Equals(movieName.ToLower().Trim())) && (movieName.Trim() != ""))
                    return true;
            }
            return false;
        }

        private List<String> movieSuggestions(String movieText)
        {
            List<String> movies = movieList();
            List<String> Suggestions = new List<String>();
            foreach (String movie in movies)
            {
                if  ( (movie.ToLower().Split('%')[0].Trim().Contains(movieText.ToLower().Trim())) || (movieText.ToLower().Trim().Contains(movie.ToLower().Split('%')[0].Trim()))  )
                    Suggestions.Add (movie.ToUpper());
            }
            return Suggestions;
        }


        private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                movieName.Text = movieSuggestions(movieName.Text).ElementAt<String>(listBox1.SelectedIndex).Split('%')[0];
            }
            catch
            {
                movieName.Text = movieName.Text;
            }
        }

		private void Button_Click_1(object sender, RoutedEventArgs e)
		{
            SlideTransition rotatetransition = new SlideTransition();
            ITransition transition;
            if (isCorrect(movieName.Text))
            {
                
                GlobalVariables.movieName = movieName.Text;

                TurnstileTransition trns;
                trns = new TurnstileTransition();
                trns.Mode = TurnstileTransitionMode.BackwardOut;
                ITransition transition0 = trns.GetTransition(LayoutRoot);
                transition0.Completed += delegate { transition0.Stop(); };
                transition0.Begin();

                NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative));
            }

            listBox1.ItemsSource = from item in movieSuggestions(movieName.Text) select new movieItem { MovieName = item.Split('%')[0] , MovieInfo = item.Split('%')[1]};         
            rotatetransition.Mode = SlideTransitionMode.SlideLeftFadeIn;
            transition = rotatetransition.GetTransition(listBox1);
            transition.Completed += delegate { transition.Stop(); };
            transition.Begin();


           
		}

       
	}
}